package com.cpimex.eprice.action;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.sql.DataSource;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.apache.struts.upload.FormFile;

import com.cpimex.eprice.action.plugin.ConnectionBuilder;
import com.cpimex.eprice.forms.UploadForm;
import com.cpimex.eprice.model.Upload;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.sql.DataSource;


/**
 * 
 * @author Luis Celis
 *
 */
public class uploadService extends MappingDispatchAction {
	static private final int TIMEOUT = 600;
	
	/**
	 * 
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward list(ActionMapping mapping, 
			ActionForm form,
			HttpServletRequest request, 
			HttpServletResponse response)throws Exception {
		InitialContext context = new InitialContext();
		//DataSource dataSrc = (DataSource) context.lookup("java:comp/env/jdbc/Eprice");
		//Connection conn = ConnectionBuilder.epriceConnection(context);
		DataSource dataSrc = (DataSource) context.lookup("java:comp/env/jdbc/Eprice");
		Connection conn = dataSrc.getConnection();
		
		
		try{
			
			String str_detalle      = request.getParameter("str_detalle");
			String str_cliente      = request.getParameter("str_cliente");
			String str_producto     = request.getParameter("str_producto");
			String str_descProducto = request.getParameter("str_descProducto");
		
			Map map_parametro = new HashMap();
			map_parametro.put("str_detalle",      str_detalle);
			map_parametro.put("str_cliente",      str_cliente);
			map_parametro.put("str_producto",     str_producto);
			map_parametro.put("str_descProducto", str_descProducto);
			
			ArrayList arrL_documentos = Upload.list(conn, str_detalle);
			
			request.setAttribute("map_parametro", map_parametro);
			request.setAttribute("arrL_documentos", arrL_documentos);
			
			return mapping.findForward("edit_Upload");
		}catch(Exception ex){
			throw ex;
		}finally{
			conn.close();
		}	
	}

	
	/**
	 * Muestra la edicion para subir archivo
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward editUpload(ActionMapping mapping, 
			ActionForm form,
			HttpServletRequest request, 
			HttpServletResponse response)throws Exception {
		UploadForm forma  = (UploadForm) form;

		String str_detalle      = request.getParameter("str_detalle");
		String str_cliente      = request.getParameter("str_cliente");
		String str_producto     = request.getParameter("str_producto");
		String str_descProducto = request.getParameter("str_descProducto");
	
		Map map_parametro = new HashMap();
		map_parametro.put("str_detalle",      str_detalle);
		map_parametro.put("str_cliente",      str_cliente);
		map_parametro.put("str_producto",     str_producto);
		map_parametro.put("str_descProducto", str_descProducto);
		request.setAttribute("map_parametro", map_parametro);
		
		forma.setStr_cliente(str_cliente);
		forma.setStr_detalle(str_detalle);
		forma.setStr_producto(str_producto);

		return mapping.findForward("edit_Upload");
	}
	
	
	/**
	 * 
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward fileUpload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception {
		InitialContext context = new InitialContext();
		//DataSource dataSrc = (DataSource) context.lookup("java:comp/env/jdbc/Eprice");
		//Connection conn = ConnectionBuilder.epriceConnection(context);
		DataSource dataSrc = (DataSource) context.lookup("java:comp/env/jdbc/Eprice");
		Connection conn = dataSrc.getConnection();
		
		
		try{
			UploadForm forma  = (UploadForm) form;

			String str_detalle = request.getParameter("str_detalle");
			String str_cliente = request.getParameter("str_cliente");
			String str_producto = request.getParameter("str_producto");
			String str_descripcion = request.getParameter("str_descripcion");

			ServletContext sc  =  getServlet().getServletContext();
			String str_filePath = sc.getRealPath("/");
			str_filePath += "archivo\\";
			FormFile file_archivo = forma.getTheFile();

			byte[] byte_archivo   = file_archivo.getFileData();
			String str_nombreArchivo   = file_archivo.getFileName();
			file_archivo.getContentType();

			System.out.println(str_filePath);
			com.cpimex.eprice.model.Upload.fileWrite(conn, str_filePath, str_detalle, str_cliente, str_producto, str_descripcion, str_nombreArchivo, byte_archivo);

			return mapping.findForward("file_Upload");

		}catch(Exception ex){
			throw ex;
		}finally{
			conn.close();
		}
	}


	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public void deleteUpload(ActionMapping mapping, 
			ActionForm form,
			HttpServletRequest request, 
			HttpServletResponse response)throws Exception {
		
		InitialContext context = new InitialContext();
		//DataSource dataSrc = (DataSource) context.lookup("java:comp/env/jdbc/Eprice");
		//Connection conn = ConnectionBuilder.epriceConnection(context);
		DataSource dataSrc = (DataSource) context.lookup("java:comp/env/jdbc/Eprice");
		Connection conn = dataSrc.getConnection();
		
				
		try{
			String str_detalle      = request.getParameter("str_detalle");
			String str_cliente      = request.getParameter("str_cliente");
			String str_producto     = request.getParameter("str_producto");
			String str_descProducto = request.getParameter("str_descProducto");
			
			String str_documento = request.getParameter("int_documento");
			
			Map map_parametro = new HashMap();
			map_parametro.put("str_detalle",      str_detalle);
			map_parametro.put("str_cliente",      str_cliente);
			map_parametro.put("str_producto",     str_producto);
			map_parametro.put("str_descProducto", str_descProducto);
			request.setAttribute("map_parametro", map_parametro);
			
			int int_documento = Integer.parseInt(str_documento);
			
			// System.out.println(int_documento + " = " + str_detalle);
			
			Upload.delete(conn, int_documento, str_detalle);
			
			ArrayList arrL_documentos = Upload.list(conn, str_detalle);
			request.setAttribute("arrL_documentos", arrL_documentos);

		}catch(Exception ex){
			throw ex;
		}finally{
			conn.close();			
		}
	}
	
	
	
	public void download(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		
		InitialContext context = new InitialContext();
		//DataSource dataSrc = (DataSource) context.lookup("java:comp/env/jdbc/Eprice");
		//Connection conn = ConnectionBuilder.epriceConnection(context);
		DataSource dataSrc = (DataSource) context.lookup("java:comp/env/jdbc/Eprice");
		Connection conn = dataSrc.getConnection();
		
				
		try{
		    String str_documento = request.getParameter("int_documento");
		    String str_detalle   = request.getParameter("str_detalle");
		    
		    
		    Map map_file = Upload.download(conn, str_detalle, str_documento);
		    
		    byte byte_file[]         = (byte[])map_file.get("byte_file");
		    String str_mimeType      = (String) map_file.get("mimeType");
		    String str_internodocsol = (String) map_file.get("str_internodocsol");
		    int int_size             = ((Integer) map_file.get("int_size")).intValue();
		    
		    if(byte_file!=null){
		    	 response.setContentLength(int_size);
		 	    response.setContentType(str_mimeType);
		 	    response.setHeader("Content-disposition","attachment; filename=" + str_internodocsol);
		 	    response.setHeader("Cache-Control","max-age=" + TIMEOUT);
		 	    ServletOutputStream outStream = response.getOutputStream();
		 	    outStream.flush();
		 	    
		 	   try{
		 		   if(byte_file!=null){
		 			   outStream.write(byte_file);
					}
		 	   }catch(Exception ex){
		 		   throw ex;
				}finally{
					outStream.flush();
					outStream.close();
				}	    	
			}else{

			}
		}catch(Exception ex){
			throw ex;
		}finally{
			conn.close();
		}
	    
	  }	
}